package com.archstudy.springcloud.message.service.impl.messageDispatch;

import com.archstudy.springcloud.message.service.impl.MessagePushServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.concurrent.Executor;

@Component
@Slf4j
public class MessageRelayKafkaService implements ApplicationContextAware {

    @Value("${kafka.relay.topic}")
    private String relayTopic;

    @Value("${kafka.relay.consumer-count:1}")
    private int consumerCount;

    @Value("${kafka.relay.consumer-handler-count:10}")
    private int handlerCount;

    @Autowired()
    @Qualifier("relayConsumerExecutor")
    private Executor relayConsumerExecutor;

    private ApplicationContext applicationContext;

    @Autowired
    private MessagePushServiceImpl messagePushService;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @PostConstruct
    public void init() {
        for(int i = 0; i < consumerCount; i++){

            KafkaConsumer relayKafkaConsumer = applicationContext.getBean(KafkaConsumer.class);
            relayKafkaConsumer.subscribe(Collections.singletonList(relayTopic));
            RelayMessageDispatcher relayMessageDispatcher = new RelayMessageDispatcher(relayKafkaConsumer,messagePushService,handlerCount);
            relayConsumerExecutor.execute(relayMessageDispatcher);
        }
    }


}
